package main

import (
	"log"
	"net"
	"time"

	"test.com/fusion"
	"test.com/login/session"
	"test.com/protocol"
)

func runCenterServerConnector() {
	var addr = cfg.CenterServerHost + cfg.LoginServerListen
	log.Printf("start center server connector `%s` goroutine successfully.\n", addr)

	for !fusion.IsStopService {
		conn, err := net.Dial("tcp", addr)
		if err != nil {
			log.Printf("connect center `%s` failed, %s.\n", addr, err)
			time.Sleep(time.Second)
			continue
		}
		log.Printf("connect center `%s` successfully.\n", addr)
		fusion.SafeConnHandler(runCenterServerHandler)(conn)
	}
}

func runCenterServerHandler(conn net.Conn) {
	var obj = session.InstCenterServer
	obj.InitAndStartSendCoroutine(&inst.ServiceBase, conn)
	obj.SendRegister()
	defer func() {
		obj.ShutdownAndStopSendCoroutine(false)
	}()
	obj.RunRecvCoroutine(protocol.SLC_RPC_INVOKE_RESP, func(pck *fusion.NetPacket) int {
		var handler = session.CenterServerSessionHandlers[pck.Opcode]
		if handler != nil {
			return handler(obj, pck)
		}
		var rpcHandler = session.CenterServerSessionRPCHandlers[pck.Opcode]
		if rpcHandler != nil {
			return rpcHandler(obj, pck, fusion.ReadRPCReqMetaInfo(pck))
		}
		return fusion.SessionHandleUnhandle
	})
}
